/**
 *
 */
package main

import (
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"log"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"
)

type gift struct {
	Id      int    // 奖品ID
	Name    string // 奖品名称
	Pic     string // 奖品图片
	Link    string // 奖品链接
	Inuse   bool   // 是否使用中
	Rate    int    // 中奖概率，万分之N。0-9999
	RateMin int    // 大于等于最小中奖编码
	RateMax int    // 小于等于最大中奖编码
}

const (
	// 最大的中奖号码
	rateMax = 10
)

var (
	logger *log.Logger

	// 奖品列表
	giftList []*gift
)

type lotteryController struct {
	Ctx iris.Context
}

// 初始化日志
func initLog() {
	f, _ := os.Create("C:\\Users\\Administrator\\Desktop\\log\\lottery_demo.log")
	logger = log.New(f, "", log.Ldate|log.Lmicroseconds)
}

func newApp() (app *iris.Application) {
	app = iris.New()
	mvc.New(app.Party("/")).Handle(&lotteryController{})

	initLog()

	return app
}

func main() {
	var (
		app *iris.Application
	)

	app = newApp()
	_ = app.Run(iris.Addr(":8080"))
}

func newGift() *[5]gift {
	giftList := new([5]gift)
	g1 := gift{
		Id:      1,
		Name:    "富强福",
		Pic:     "富强福.jpg",
		Link:    "",
		Inuse:   true,
		Rate:    0,
		RateMin: 0,
		RateMax: 0,
	}
	giftList[0] = g1

	g2 := gift{
		Id:      2,
		Name:    "和谐福",
		Pic:     "和谐福.jpg",
		Link:    "",
		Inuse:   true,
		Rate:    0,
		RateMin: 0,
		RateMax: 0,
	}
	giftList[1] = g2

	g3 := gift{
		Id:      3,
		Name:    "友善福",
		Pic:     "友善福.jpg",
		Link:    "",
		Inuse:   true,
		Rate:    0,
		RateMin: 0,
		RateMax: 0,
	}
	giftList[2] = g3

	g4 := gift{
		Id:      4,
		Name:    "爱国福",
		Pic:     "爱国福.jpg",
		Link:    "",
		Inuse:   true,
		Rate:    0,
		RateMin: 0,
		RateMax: 0,
	}
	giftList[3] = g4

	g5 := gift{
		Id:      5,
		Name:    "敬业福",
		Pic:     "敬业福.jpg",
		Link:    "",
		Inuse:   true,
		Rate:    0,
		RateMin: 0,
		RateMax: 0,
	}
	giftList[4] = g5

	return giftList
}

func giftRage(rate string) *[5]gift {
	giftList := newGift()
	rates := strings.Split(rate, ",")
	rateLen := len(rates)

	// 整理中间区间数据
	rateStart := 0

	for i, data := range giftList {
		if !data.Inuse {
			continue
		}

		grate := 0
		if i < rateLen {
			grate, _ = strconv.Atoi(rates[i])
		}

		giftList[i].Rate = grate
		giftList[i].RateMin = rateStart
		giftList[i].RateMax = rateStart + grate

		if giftList[i].RateMax >= rateMax {
			giftList[i].RateMax = rateMax
			rateStart = 0
		} else {
			rateStart += grate
		}
	}
	fmt.Printf("giftlist=%v\n", giftList)
	return giftList
}

func (c *lotteryController) Get() string {
	rate := c.Ctx.URLParamDefault("rate", "4,3,2,1,0")
	giftList := giftRage(rate)
	return fmt.Sprintf("%v\n", giftList)
}

func (c *lotteryController) GetLucky() (result map[string]interface{}) {

	var (
		code     int32
		ok       bool
		sendData string
		uid      int
	)

	uid, _ = c.Ctx.URLParamInt("uid")
	rate := c.Ctx.URLParamDefault("rate", "4,3,2,1,0")

	code = luckyCode()

	result = make(map[string]interface{})
	result["success"] = ok

	giftList := giftRage(rate)

	for _, data := range giftList {
		if !data.Inuse {
			continue
		}

		if data.RateMin <= int(code) && data.RateMax > int(code) {
			// 中奖了，抽奖编码在奖品编码范围内
			// 开始发奖
			ok = true
			sendData = data.Pic
			if ok {
				// 中奖后，成功得到产品
				// 生成中奖纪录
				saveLuckData(code, data.Id, data.Name, data.Link, sendData)
				result["success"] = ok
				result["uid"] = uid
				result["id"] = data.Id
				result["name"] = data.Name
				result["link"] = data.Link
				result["data"] = sendData
				break
			}
		}
	}
	return
}

func luckyCode() (code int32) {
	var (
		seed int64
	)
	seed = time.Now().UnixNano()
	code = rand.New(rand.NewSource(seed)).Int31n(int32(rateMax))
	return
}

// 纪录用户的获奖信息
func saveLuckData(code int32, id int, name string, link string, sendData string) {
	logger.Printf("lucky, code=%d, gift=%d, name=%s, link=%s, data=%s \n", code, id, name, link, sendData)
}
